/**
 * Copyright (c) 2015, 玛雅牛［李飞］ (lifei@wellbole.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jfinal.plugin.zbus.sender;

import java.io.IOException;

import org.zstacks.zbus.client.Producer;
import org.zstacks.zbus.client.ZbusException;
import org.zstacks.znet.Message;

import com.jfinal.plugin.zbus.Zbus;
import com.jfinal.plugin.zbus.coder.Coder;

/**
 * @ClassName: MqSender
 * @Description: Mq泛型发送器
 * @author 李飞 (lifei@wellbole.com)
 * @date 2015年8月2日 下午6:46:51
 * @since V1.0.0
 */
public class MqSender<T> implements Sender<T>{
	/**
	 * 生产者
	 */
	private final Producer producer;
	
	/**
	 * 编码解码器
	 */
	private final Coder coder;

	/**
	 * <p>
	 * Title: Sender
	 * </p>
	 * <p>
	 * Description: 构建一个MQ发送器
	 * </p>
	 * 
	 * @param mq
	 *            MQ队列名
	 * @since V1.0.0
	 */
	public MqSender(String mq) {
		this.producer = Zbus.findProducerBy(mq);
		if (null == this.producer) {
			throw new ZbusException("Can not find (mq=" + mq + ")");
		}
		this.coder = Zbus.getCoder();
	}

	/**
	 * @Title: send
	 * @Description: 发送对象到Mq
	 * @param obj
	 *            发送对象
	 * @throws ZbusException
	 * @since V1.0.0
	 */
	public void send(T obj) throws ZbusException {
		//编码
		Message msg = this.coder.encode(obj);
		try {
			producer.sendSync(msg, Zbus.DEFAULT_TIMEOUT);
		} catch (IOException e) {
			throw new ZbusException(e.getMessage(), e);
		}
	}
}
